package org.syyo.admin.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.syyo.admin.anno.SysLog;
import org.syyo.admin.domain.OpLog;
import org.syyo.admin.domain.response.UserResp;
import org.syyo.admin.mapper.OpLogMapper;
import org.syyo.admin.mapper.UserMapper;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Auther: wangzhong
 * @Date: 2019/10/11 11:42
 * @Description: 记录系统操作日志,使用这个，所有接口只能有一个参数
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OpLogMapper opLogMapper;

    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint pjp,SysLog log) throws Throwable {

        // 执行方法
        Object proceed = pjp.proceed();

        //获取注解上的数据
        String title = log.value();

        //记录日志
        saveSysLog(pjp,title);

        return proceed;
    }

    private void saveSysLog(ProceedingJoinPoint pjp,String title) {
        OpLog opLog = new OpLog();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();

        //请求的方法名
        String className = pjp.getTarget().getClass().getName();
        String methodName = signature.getName();
        opLog.setMethod(className + "." + methodName + "()");

        //请求的参数
        String param = "";
        Object[] args = pjp.getArgs();
        if (args != null && args.length > 0){
            param = JSON.toJSONString(args[0]);
        }

//        //获取request
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        String ip = request.getRemoteAddr();
//        String token = request.getHeader("X-Token");
//        UserResp userResp = userMapper.findUserByToken(token);
//        opLog.setIp(ip);
//        Date date = new Date();
//        opLog.setOperDate(date);
//        opLog.setTitle(title);
//        opLog.setContent(param);
//        opLog.setUserId(userResp.getUserId());
//        //添加系统日志
//        opLogMapper.addOpLog(opLog);
    }
}
